//
//  MyAdressContractsViewModel.m
//  Yihubang
//
//  Created by xmy on 16/10/19.
//  Copyright © 2016年 xmy. All rights reserved.
//

#import "MyAdressContractsViewModel.h"
#import <AddressBook/AddressBook.h>
@interface MyAdressContractsViewModel()
@property (nonatomic, strong) NSArray * sectionArr;
@end

@implementation MyAdressContractsViewModel
-(void)initialize{
    [super initialize];
    @weakify(self);
    [[[RACObserve(self, dataSource)
       filter:^(NSArray *events) {
           return @(events.count > 0).boolValue;
       }]
      deliverOnMainThread]
     subscribeNext:^(NSArray *events) {
         @strongify(self)
         [self.mTableView reloadData];
     }];
    [self.viewController showHUDWithString:@"加载数据..."];
    [self loadPerson];
}

-(NSArray *)sectionArr{
    if(!_sectionArr){
        _sectionArr =[NSArray array];
    }
    return _sectionArr;
}

- (RACSignal*)requestRemoteDataSignalWithPage:(NSUInteger)page
{

    return [RACSignal empty];
}

- (void)loadPerson
{
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
//            [hud turnToError:@"没有获取通讯录权限"];
        });
    }
}

- (void)copyAddressBook:(ABAddressBookRef)addressBook
{
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSMutableDictionary * contracts =[NSMutableDictionary dictionary];
    for ( int i = 0; i < numberOfPeople; i++){
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        NSString * name =[NSString string];
        if(lastName !=nil){
            name =lastName;
        }
        if(name !=nil && firstName !=nil){
            name = [name stringByAppendingString:firstName];
        }else{
            if(firstName ==nil){
                name = lastName;
            }else{
                name = firstName;
            }
        }
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
         NSMutableArray * phones =[NSMutableArray array];
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
//            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            if ([personPhone hasPrefix:@"+"]) {
                personPhone = [personPhone substringFromIndex:3];
            }
            
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            [phones addObject:personPhone];
        }
        NSMutableArray * initialArr;//首字母分组
        if(phones.count >0){
            if(name.length ==0){
                name = phones[0];
            }
            NSString *  initial = [[self transform:name] substringToIndex :1];
            if([self characterOr:initial] ==NO){
                initial =@"#";
            }
            if([[contracts allKeys] containsObject: initial]){
                initialArr = contracts[initial];
            }else{
                initialArr =[NSMutableArray array];
            }
            NSDictionary * personInfo =@{@"personName":name,@"personPhones":phones};
            [initialArr addObject:personInfo];
            [contracts setObject:initialArr forKey:initial];
        }
    }
     [self.viewController hiddenHUD];
    self.dataSource = [self sortedArrayTo:contracts];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25.f;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * back = [UIView new];
    back.backgroundColor = [UIColor whiteColor];
    back.frame = CGRectMake(0, 0, ScreenWidth, 25);
    UILabel * title  =[UILabel new];
    title.textColor = [UIColor colorWithHex:0xA8A8A8];
//    title.alpha = .4f;
    title.frame = CGRectMake(10, 0, ScreenWidth, 25);
    title.text = self.sectionArr[section];
    [back addSubview:title];
    return back;

}
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sectionArr;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{

    return index;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * object = self.dataSource[indexPath.section][indexPath.row];
    NSArray * phones = object[@"personPhones"];
    if(phones.count > 1){
        [self showPhonesArrActionSheet:object];
    }else{
        [self.didSelectCommand execute:object];
    }
    
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    cell.textLabel.textColor = [UIColor colorWithHex:0xA8A8A8];
//    cell.backgroundColor =[UIColor clearColor];
    cell.textLabel.text = object[@"personName"];
}
- (NSString *)transform:(NSString *)chinese
{
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    return [pinyin uppercaseString];
}
-(NSArray *)sortedArrayTo :(NSMutableDictionary *)contracts{
    NSArray *keys = [contracts allKeys];
    self.sectionArr = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableArray * sortContracts =[NSMutableArray array];
    for (NSString *categoryId in self.sectionArr) {
        [sortContracts addObject:[contracts objectForKey:categoryId]];
    }
    return sortContracts;
}

-(BOOL) characterOr:(NSString *)initial{
    unichar c=[initial characterAtIndex:0];
    if((c<'A'||c>'Z')&&(c<'a'||c>'z')){
        return NO;
    }
    return YES;
}

- (void)showPhonesArrActionSheet:(NSDictionary*)object
{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] init];
    actionSheet.title = @"电话号码";
    [actionSheet addButtonWithTitle:@"取消"];
    NSArray * phonesArray = object[@"personPhones"];
    for (NSString* phone in phonesArray) {
        [actionSheet addButtonWithTitle:phone];
    }
    [actionSheet setCancelButtonIndex:0];
    [actionSheet showInView:self.viewController.view];
    @weakify(actionSheet)
    [actionSheet.rac_buttonClickedSignal subscribeNext:^(NSNumber *index) {
        @strongify(actionSheet)
        if (index.integerValue>0) {
            NSString* phone = [actionSheet buttonTitleAtIndex:index.integerValue];
            [self.didSelectCommand execute:@{@"personName":object[@"personName"],@"personPhones":@[phone]}];
        }
    } ];
}
@end
